import tkinter as tk
import random
from tkinter import messagebox

class MemoryMatch:
    def __init__(self, master, rows=4, cols=4):
        self.master = master
        self.master.title("记忆配对")
        self.master.resizable(False, False)
        
        # 游戏设置
        self.rows = rows
        self.cols = cols
        self.buttons = []
        self.icons = []
        self.flipped = []
        self.matched = []
        self.first_card = None
        self.second_card = None
        self.tries = 0
        self.matches = 0
        self.game_active = True
        
        # 创建UI
        self.create_ui()
        
        # 初始化游戏
        self.init_game()
    
    def create_ui(self):
        # 创建顶部信息栏
        info_frame = tk.Frame(self.master)
        info_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 尝试次数
        self.tries_var = tk.StringVar(value="尝试次数: 0")
        tries_label = tk.Label(info_frame, textvariable=self.tries_var, font=("Arial", 14))
        tries_label.pack(side=tk.LEFT)
        
        # 重置按钮
        reset_button = tk.Button(info_frame, text="重置游戏", font=("Arial", 12), command=self.reset_game)
        reset_button.pack(side=tk.RIGHT)
        
        # 创建游戏网格
        self.game_frame = tk.Frame(self.master)
        self.game_frame.pack(padx=10, pady=10)
    
    def init_game(self):
        # 清空游戏区域
        for widget in self.game_frame.winfo_children():
            widget.destroy()
        
        # 重置游戏状态
        self.buttons = []
        self.flipped = []
        self.matched = []
        self.first_card = None
        self.second_card = None
        self.tries = 0
        self.matches = 0
        self.game_active = True
        self.tries_var.set(f"尝试次数: {self.tries}")
        
        # 创建图标列表
        icons = [
            "🍎", "🍐", "🍊", "🍋", "🍌", "🍉", "🍇", "🍓",
            "🍈", "🍒", "🍑", "🥝", "🍅", "🥑", "🌶️", "🥕"
        ]
        
        # 根据网格大小选择适当数量的图标
        num_pairs = (self.rows * self.cols) // 2
        selected_icons = icons[:num_pairs] * 2
        random.shuffle(selected_icons)
        
        self.icons = selected_icons
        
        # 创建按钮网格
        for i in range(self.rows):
            row_buttons = []
            for j in range(self.cols):
                button = tk.Button(
                    self.game_frame,
                    width=5,
                    height=2,
                    font=("Arial", 24),
                    bg="#CCCCCC",
                    command=lambda row=i, col=j: self.flip_card(row, col)
                )
                button.grid(row=i, column=j, padx=5, pady=5)
                row_buttons.append(button)
            
            self.buttons.append(row_buttons)
    
    def flip_card(self, row, col):
        # 如果游戏未激活或卡片已翻开或已匹配，则不执行任何操作
        if not self.game_active or (row, col) in self.flipped or (row, col) in self.matched:
            return
        
        # 显示卡片图标
        button = self.buttons[row][col]
        icon = self.icons[row * self.cols + col]
        button.config(text=icon, bg="white")
        
        # 记录翻开的卡片
        self.flipped.append((row, col))
        
        # 处理第一张和第二张卡片
        if self.first_card is None:
            self.first_card = (row, col)
        else:
            self.second_card = (row, col)
            self.tries += 1
            self.tries_var.set(f"尝试次数: {self.tries}")
            
            # 禁用所有按钮，防止同时翻开第三张卡片
            self.disable_all_buttons()
            
            # 检查两张卡片是否匹配
            self.master.after(1000, self.check_match)
    
    def check_match(self):
        # 获取两张卡片的图标
        row1, col1 = self.first_card
        row2, col2 = self.second_card
        
        icon1 = self.icons[row1 * self.cols + col1]
        icon2 = self.icons[row2 * self.cols + col2]
        
        # 如果匹配
        if icon1 == icon2:
            self.matched.append(self.first_card)
            self.matched.append(self.second_card)
            self.matches += 1
            
            # 检查游戏是否结束
            if self.matches == (self.rows * self.cols) // 2:
                self.game_active = False
                messagebox.showinfo("游戏结束", f"恭喜你！你用了{self.tries}次尝试完成了游戏！")
        else:
            # 如果不匹配，翻回卡片
            button1 = self.buttons[row1][col1]
            button2 = self.buttons[row2][col2]
            button1.config(text="", bg="#CCCCCC")
            button2.config(text="", bg="#CCCCCC")
        
        # 重置已翻开的卡片
        self.flipped = []
        self.first_card = None
        self.second_card = None
        
        # 重新启用所有未匹配的按钮
        self.enable_all_buttons()
    
    def disable_all_buttons(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if (i, j) not in self.matched:
                    self.buttons[i][j].config(state=tk.DISABLED)
    
    def enable_all_buttons(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if (i, j) not in self.matched:
                    self.buttons[i][j].config(state=tk.NORMAL)
    
    def reset_game(self):
        self.init_game()

if __name__ == "__main__":
    root = tk.Tk()
    game = MemoryMatch(root)
    root.mainloop()